import "./index.scss"
import Link from 'next/link'

// 分页组件
function Pagination({
  currentPage,
  totalPages,
  baseUrl,
  keyword = ""
}: {
  currentPage: number
  totalPages: number
  baseUrl: string
  keyword?: string
}) {
  const pages = []
  const maxVisiblePages = 5

  let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2))
  let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1)

  if (endPage - startPage + 1 < maxVisiblePages) {
    startPage = Math.max(1, endPage - maxVisiblePages + 1)
  }

  // 构建带搜索关键词的URL
  const buildUrl = (page: number) => {
    if (keyword) {
      return `${baseUrl}?page=${page}&keyword=${encodeURIComponent(keyword)}`
    }
    return `${baseUrl}?page=${page}`
  }

  // 上一页
  if (currentPage > 1) {
    pages.push(
      <Link key="prev" href={buildUrl(currentPage - 1)} className="page-link">
        上一页
      </Link>
    )
  }

  // 页码
  for (let i = startPage; i <= endPage; i++) {
    pages.push(
      <Link
        key={i}
        href={buildUrl(i)}
        className={`page-link ${i === currentPage ? 'active' : ''}`}
      >
        {i}
      </Link>
    )
  }

  // 下一页
  if (currentPage < totalPages) {
    pages.push(
      <Link key="next" href={buildUrl(currentPage + 1)} className="page-link">
        下一页
      </Link>
    )
  }

  return <div className="pagination">{pages}</div>
}

export default async function Home({ searchParams }: {
  searchParams: { page?: string; keyword?: string; category_id?: string }
}) {
  const currentPage = Number(searchParams.page) || 1
  const keyword = searchParams.keyword || ""
  const categoryId = searchParams.category_id || "" // 添加分类ID参数
  const pageSize = 10 // 每页显示10篇文章

  try {
    // 修改API调用以支持分页和搜索
    let apiUrl = `http://127.0.0.1:9090/blog/articles/simple?page=${currentPage}&pageSize=${pageSize}`
    if (categoryId) {
      apiUrl += `&category_id=${encodeURIComponent(categoryId)}`
    }
    if (keyword) {
      apiUrl += `&keyword=${encodeURIComponent(keyword)}`
    }

    const res = await fetch(apiUrl, { cache: "no-store" })

    if (!res.ok) {
      throw new Error("Failed to fetch articles")
    }

    const result = await res.json()
    console.log("result", result)
    const articles = result.data.list
    const totalArticles = result.data.total || articles.length
    const totalPages = Math.ceil(totalArticles / pageSize)

    return (
      <div className="rightContent">
        <div className="top">
          <div>/ 理想就是人生的GPS。</div>
          <div>/ 有了GPS，你就知道往哪去。</div>
          <div>/ 尽管中间有很多拐弯，道路很曲折，但你知道你最终要去哪儿，所以你心中不慌。</div>
        </div>
        <hr />

        {articles.length === 0 ? (
          <div className="noArticle">{keyword ? `没有找到包含"${keyword}"的文章` : "暂无文章"}</div>
        ) : (
          <>
            {articles.map((article: any) => (
              <article key={article.id} className="article">
                <p className="article-time">
                  {new Date(article.createTime).toLocaleDateString("zh-CN")}
                </p>
                <a href={`/posts/${article.id}`}>{article.title}</a>
                <p className="article-category">{article.category}</p>
              </article>
            ))}
            {/* 分页控件 */}
            <div className="pagination-container">
              <Pagination
                currentPage={currentPage}
                totalPages={totalPages}
                baseUrl="/"
                keyword={keyword}
              />
            </div>
          </>
        )}
        {/* 搜索框 - 使用原生表单提交 */}
        <div className="search-container">
          <form className="search-form" method="get" action="/">
            <input
              type="text"
              placeholder="搜索文章标题..."
              name="keyword"
              defaultValue={keyword}
              className="search-input"
            />
            <input type="hidden" name="page" value="1" />
            <button type="submit" className="search-button">搜索</button>
          </form>
        </div>
      </div>
    )
  } catch (error: any) {
    return (
      <div className="">
        <p className="">加载文章失败：{error.message}</p>
      </div>
    )
  }
}